import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs/index";
import {ConfigService} from "../config.service";
import {AuthService} from "../auth.service";
import {Attachment} from "../../model/util/entity/attachment";
import {map} from "rxjs/operators";

@Injectable({
    providedIn: 'root'
})
export class AttachmentService {

    constructor(private http: HttpClient, private authService: AuthService, private configService: ConfigService) {
    }

    getOne(id: string): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.get(this.configService.api.url + '/attachments' + "/detail/" + id, options).pipe(map((res: any) => {
            const attachment = new Attachment();
            attachment.fromJSON(res);
            return attachment;
        }));
    }

    create(attachment: Attachment): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        attachment.create();
        return this.http.post(this.configService.api.url + "/attachments" + "/create", {attachment: attachment.toJSON()}, options);
    }

    createMany(attachments: Array<Attachment>): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.post(this.configService.api.url + "/attachments" + "/create/many", {attachments: attachments}, options);
    }

    update(attachment: Attachment): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.post(this.configService.api.url + "/attachments" + "/" + attachment._id + "/update", {attachment: attachment.toJSON()}, options);
    }

    delete(id: string): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.get(this.configService.api.url + "/attachments" + "/" + id + "/remove", options);
    }

}
